package org.example.demo1.DAO;

import org.example.demo1.util.DBUtil;
import org.example.demo1.entity.Student;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StudentDAO {
    public static final int PAGE_SIZE = 5;
     // 每页显示的数据条数
    public List<Student> getStudentsByPage(int pageNum) {
        List<Student> studentList = new ArrayList<>();
        String sql = "SELECT * FROM students LIMIT ?,?";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            int startIndex = (pageNum - 1) * PAGE_SIZE;
            preparedStatement.setInt(1, startIndex);
            preparedStatement.setInt(2, PAGE_SIZE);
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                while (resultSet.next()) {
                    Student student = new Student();
                    student.setId(resultSet.getInt("id"));
                    student.setName(resultSet.getString("name"));
                    student.setAge(resultSet.getInt("age"));
                    studentList.add(student);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return studentList;
    }
    public int getTotalCount() {
        int count = 0;
        String sql = "SELECT COUNT(*) FROM students";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql);
             ResultSet resultSet = preparedStatement.executeQuery()) {
            if (resultSet.next()) {
                count = resultSet.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
}
}
